<?php

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\model\RoleMenu;

class Menu extends MenuBase
{
    protected $middleware = [Auth::class];

    public function getServerMenu()
    {
        $query = \app\model\Menu::field(['id', 'name', 'path', 'label', 'sort', 'icon', 'visible']);

        if (request()->user->id !== 1) {
            $roleIds = array_column(request()->user->roles->toArray(), 'id');
            $menuIds = RoleMenu::where('role_id', 'in',  $roleIds)->distinct(true)->field('menu_id')->select();
            $query->where('id', 'in', array_column($menuIds->toArray(), 'menu_id'));
        }

        $models = $query->select()->map(function ($item) {
            return [
                'id' => $item->id,
                'name' => $item->name,
                'path' => $item->path,
                'meta' => [
                    'locale' => $item->label,
                    'icon' => $item->icon,
                    'order' => $item->sort,
                    'hideInMenu' => $item->visible === '0'
                ]
            ];
        });

        return json(['code' => 20000, 'data' => $models]);
    }
}
